home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / non-ANSI / c-client / os_sv4.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-06-07  |  21.3 KB  |  799 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- SVR4 version
  3.  *
  4.  * Author:    Mark Crispin
  5.  *        Networks and Distributed Computing
  6.  *        Computing & Communications
  7.  *        University of Washington
  8.  *        Administration Building, AG-44
  9.  *        Seattle, WA  98195
  10.  *        Internet: MRC@CAC.Washington.EDU
  11.  *
  12.  * Date:    10 April 1992
  13.  * Last Edited:    7 June 1993
  14.  *
  15.  * Copyright 1993 by the University of Washington
  16.  *
  17.  *  Permission to use, copy, modify, and distribute this software and its
  18.  * documentation for any purpose and without fee is hereby granted, provided
  19.  * that the above copyright notice appears in all copies and that both the
  20.  * above copyright notice and this permission notice appear in supporting
  21.  * documentation, and that the name of the University of Washington not be
  22.  * used in advertising or publicity pertaining to distribution of the software
  23.  * without specific, written prior permission.  This software is made
  24.  * available "as is", and
  25.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  26.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  27.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  28.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  29.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  30.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  31.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  32.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  33.  *
  34.  */
  35.  
  36. /* TCP input buffer */
  37.  
  38. #define BUFLEN 8192
  39.  
  40.  
  41. /* TCP I/O stream (must be before osdep.h is included) */
  42.  
  43. #define TCPSTREAM struct tcp_stream
  44. TCPSTREAM {
  45.   char *host;            /* host name */
  46.   char *localhost;        /* local host name */
  47.   int tcpsi;            /* input socket */
  48.   int tcpso;            /* output socket */
  49.   int ictr;            /* input counter */
  50.   char *iptr;            /* input pointer */
  51.   char ibuf[BUFLEN];        /* input buffer */
  52. };
  53.  
  54.  
  55. #include "osdep.h"
  56. #include <ctype.h>
  57. #include <sys/tiuser.h>
  58. #include <sys/stropts.h>
  59. #include <sys/poll.h>
  60. #include <netinet/in.h>
  61. #include <netdb.h>
  62. #include <ctype.h>
  63. #include <regexpr.h>
  64. #include <errno.h>
  65. #include <pwd.h>
  66. #include <shadow.h>
  67. #include <syslog.h>
  68. #include <sys/file.h>
  69. #include <sys/stat.h>
  70. #include <sys/socket.h>
  71. #include "mail.h"
  72. #include "misc.h"
  73.  
  74. extern int sys_nerr;
  75. extern char *sys_errlist[];
  76.  
  77. #define toint(c)    ((c)-'0')
  78. #define isodigit(c)    (((unsigned)(c)>=060)&((unsigned)(c)<=067))
  79.  
  80. /* Write current time in RFC 822 format
  81.  * Accepts: destination string
  82.  */
  83.  
  84. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  85.  
  86. void rfc822_date (date)
  87.     char *date;
  88. {
  89.   int zone,dstnow;
  90.   struct tm *t;
  91.   int time_sec = time (0);
  92.   t = localtime (&time_sec);    /* convert to individual items */
  93.   tzset ();            /* initialize timezone/daylight variables */
  94.                 /* see if it is DST now */
  95.   dstnow = daylight && t->tm_isdst;
  96.                 /* get timezone value */
  97.   zone = - (dstnow ? altzone : timezone) / 60;
  98.                 /* and output it */
  99.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  100.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  101.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,
  102.        tzname[dstnow]);
  103. }
  104.  
  105. /* Get a block of free storage
  106.  * Accepts: size of desired block
  107.  * Returns: free storage block
  108.  */
  109.  
  110. void *fs_get (size)
  111.     size_t size;
  112. {
  113.   void *block = malloc (size);
  114.   if (!block) fatal ("Out of free storage");
  115.   return (block);
  116. }
  117.  
  118.  
  119. /* Resize a block of free storage
  120.  * Accepts: ** pointer to current block
  121.  *        new size
  122.  */
  123.  
  124. void fs_resize (block,size)
  125.     void **block;
  126.     size_t size;
  127. {
  128.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  129. }
  130.  
  131.  
  132. /* Return a block of free storage
  133.  * Accepts: ** pointer to free storage block
  134.  */
  135.  
  136. void fs_give (block)
  137.     void **block;
  138. {
  139.   free (*block);
  140.   *block = NIL;
  141. }
  142.  
  143.  
  144. /* Report a fatal error
  145.  * Accepts: string to output
  146.  */
  147.  
  148. void fatal (string)
  149.     char *string;
  150. {
  151.   mm_fatal (string);        /* output the string */
  152.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  153.   abort ();            /* die horribly */
  154. }
  155.  
  156. /* Copy string with CRLF newlines
  157.  * Accepts: destination string
  158.  *        pointer to size of destination string
  159.  *        source string
  160.  *        length of source string
  161.  */
  162.  
  163. char *strcrlfcpy (dst,dstl,src,srcl)
  164.     char **dst;
  165.     unsigned long *dstl;
  166.     char *src;
  167.     unsigned long srcl;
  168. {
  169.   long i,j;
  170.   char *d = src;
  171.                 /* count number of LF's in source string(s) */
  172.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  173.   if (i > *dstl) {        /* resize if not enough space */
  174.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  175.     *dst = (char *) fs_get ((*dstl = i) + 1);
  176.   }
  177.   d = *dst;            /* destination string */
  178.                 /* copy strings, inserting CR's before LF's */
  179.   while (srcl--) switch (*src) {
  180.   case '\015':            /* unlikely carriage return */
  181.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  182.     if (srcl && *src == '\012') {
  183.       *d++ = *src++;
  184.       srcl--;
  185.     }
  186.     break;
  187.   case '\012':            /* line feed? */
  188.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  189.   default:            /* ordinary chararacter */
  190.     *d++ = *src++;        /* just copy character */
  191.     break;
  192.   }
  193.   *d = '\0';            /* tie off destination */
  194.   return *dst;            /* return destination */
  195. }
  196.  
  197.  
  198. /* Length of string after strcrlflen applied
  199.  * Accepts: source string
  200.  *        length of source string
  201.  */
  202.  
  203. unsigned long strcrlflen (s)
  204.     STRING *s;
  205. {
  206.   unsigned long pos = GETPOS (s);
  207.   unsigned long i = SIZE (s);
  208.   unsigned long j = i;
  209.   while (j--) switch (SNX (s)) {/* search for newlines */
  210.   case '\015':            /* unlikely carriage return */
  211.     if (j && (CHR (s) == '\012')) {
  212.       SNX (s);            /* eat the line feed */
  213.       j--;
  214.     }
  215.     break;
  216.   case '\012':            /* line feed? */
  217.     i++;
  218.   default:            /* ordinary chararacter */
  219.     break;
  220.   }
  221.   SETPOS (s,pos);        /* restore old position */
  222.   return i;
  223. }
  224.  
  225. /* Server log in
  226.  * Accepts: user name string
  227.  *        password string
  228.  *        optional place to return home directory
  229.  * Returns: T if password validated, NIL otherwise
  230.  */
  231.  
  232. long server_login (user,pass,home,argc,argv)
  233.     char *user;
  234.     char *pass;
  235.     char **home;
  236.     int argc;
  237.     char *argv[];
  238. {
  239.   struct passwd *pw = getpwnam (lcase (user));
  240.   struct spwd *sp;
  241.                 /* no entry for this user or root */
  242.   if (!(pw && pw->pw_uid)) return NIL;
  243.                 /* validate password and password aging */
  244.   sp = getspnam (pw->pw_name);
  245.   if (strcmp (sp->sp_pwdp, (char *) crypt (pass,sp->sp_pwdp))) return NIL;
  246.   else if ((sp->sp_lstchg > 0) && (sp->sp_max > 0) &&
  247.        ((sp->sp_lstchg + sp->sp_max) < (time (0) / (60*60*24))))
  248.     return NIL;
  249.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  250.   initgroups (user,pw->pw_gid);    /* initialize groups */
  251.   setuid (pw->pw_uid);
  252.                 /* note home directory */
  253.   if (home) *home = cpystr (pw->pw_dir);
  254.   return T;
  255. }
  256.  
  257. /* Return my user name
  258.  * Returns: my user name
  259.  */
  260.  
  261. char *myuname = NIL;
  262.  
  263. char *myusername ()
  264. {
  265.   return myuname ? myuname : (myuname = cpystr(getpwuid(geteuid ())->pw_name));
  266. }
  267.  
  268.  
  269. /* Return my home directory name
  270.  * Returns: my home directory name
  271.  */
  272.  
  273. char *hdname = NIL;
  274.  
  275. char *myhomedir ()
  276. {
  277.   return hdname ? hdname : (hdname = cpystr (getpwuid (geteuid ())->pw_dir));
  278. }
  279.  
  280.  
  281. /* Build status lock file name
  282.  * Accepts: scratch buffer
  283.  *        file name
  284.  * Returns: name of file to lock
  285.  */
  286.  
  287. char *lockname (tmp,fname)
  288.     char *tmp;
  289.     char *fname;
  290. {
  291.   int i;
  292.   sprintf (tmp,"/tmp/.%s",fname);
  293.   for (i = 6; i < strlen (tmp); ++i) if (tmp[i] == '/') tmp[i] = '\\';
  294.   return tmp;            /* note name for later */
  295. }
  296.  
  297. /* TCP/IP open
  298.  * Accepts: host name
  299.  *        contact port number
  300.  * Returns: TCP/IP stream if success else NIL
  301.  */
  302.  
  303. TCPSTREAM *tcp_open (host,port)
  304.     char *host;
  305.     int port;
  306. {
  307.   TCPSTREAM *stream = NIL;
  308.   int sock;
  309.   char *s;
  310.   struct sockaddr_in sin;
  311.   struct hostent *host_name;
  312.   char hostname[MAILTMPLEN];
  313.   char tmp[MAILTMPLEN];
  314.     extern int t_errno;
  315.     extern char *t_errlist[];
  316.     struct t_call *sndcall;
  317.  
  318.   /* The domain literal form is used (rather than simply the dotted decimal
  319.      as with other Unix programs) because it has to be a valid "host name"
  320.      in mailsystem terminology. */
  321.                 /* look like domain literal? */
  322.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  323.     strcpy (hostname,host+1);    /* yes, copy number part */
  324.     hostname[(strlen (hostname))-1] = '\0';
  325.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  326.       sin.sin_family = AF_INET;    /* family is always Internet */
  327.       strcpy (hostname,host);    /* hostname is user's argument */
  328.     }
  329.     else {
  330.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  331.       mm_log (tmp,ERROR);
  332.       return NIL;
  333.     }
  334.   }
  335.  
  336.   else {            /* lookup host name, note that brain-dead Unix
  337.                    requires lowercase! */
  338.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  339.     if ((host_name = gethostbyname (lcase (hostname)))) {
  340.                 /* copy address type */
  341.       sin.sin_family = host_name->h_addrtype;
  342.                 /* copy host name */
  343.       strcpy (hostname,host_name->h_name);
  344.                 /* copy host addresses */
  345.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  346.     }
  347.     else {
  348.       sprintf (tmp,"No such host as %.80s",host);
  349.       mm_log (tmp,ERROR);
  350.       return NIL;
  351.     }
  352.   }
  353.  
  354.                 /* copy port number in network format */
  355.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  356.  
  357.                 /* get a TCP stream */
  358.   t_errno = 0;
  359.   if (((sock = t_open ("/dev/tcp", O_RDWR, 0)) < 0) ||
  360.       (t_bind (sock, 0, 0) < 0) ||
  361.       ((sndcall = (struct t_call *) t_alloc (sock, T_CALL, T_ADDR)) == 0))
  362.   {
  363.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  364.     mm_log (tmp,ERROR);
  365.     return NIL;
  366.   }
  367.                 /* connect to address. */
  368.   sndcall->addr.len = sndcall->addr.maxlen = sizeof (sin);
  369.   sndcall->addr.buf = (char *) &sin;
  370.   sndcall->opt.len = 0;
  371.   sndcall->udata.len = 0;
  372.   if (t_connect (sock, sndcall, 0) < 0) {
  373.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  374.          t_errlist[t_errno]);
  375.     mm_log (tmp,ERROR);
  376.     return NIL;
  377.   }
  378.                 /* push streams module for read()/write(). */
  379.   if (ioctl (sock, I_PUSH, "tirdwr") < 0) {
  380.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  381.     mm_log (tmp,ERROR);
  382.     return NIL;
  383.   }
  384.                 /* create TCP/IP stream */
  385.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  386.                 /* copy official host name */
  387.   stream->host = cpystr (hostname);
  388.                 /* get local name */
  389.   gethostname (tmp,MAILTMPLEN-1);
  390.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  391.                   host_name->h_name : tmp);
  392.                 /* init sockets */
  393.   stream->tcpsi = stream->tcpso = sock;
  394.   stream->ictr = 0;        /* init input counter */
  395.   return stream;        /* return success */
  396. }
  397.  
  398. /* TCP/IP authenticated open
  399.  * Accepts: host name
  400.  *        service name
  401.  * Returns: TCP/IP stream if success else NIL
  402.  */
  403.  
  404. TCPSTREAM *tcp_aopen (host,service)
  405.     char *host;
  406.     char *service;
  407. {
  408.   TCPSTREAM *stream = NIL;
  409.   struct hostent *host_name;
  410.   char hostname[MAILTMPLEN];
  411.   int i;
  412.   int pipei[2],pipeo[2];
  413.   /* The domain literal form is used (rather than simply the dotted decimal
  414.      as with other Unix programs) because it has to be a valid "host name"
  415.      in mailsystem terminology. */
  416.                 /* look like domain literal? */
  417.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  418.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  419.     hostname[i-1] = '\0';
  420.   }
  421.                 /* note that Unix requires lowercase! */
  422.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  423.     strcpy (hostname,host_name->h_name);
  424.                 /* make command pipes */
  425.   if (pipe (pipei) < 0) return NIL;
  426.   if (pipe (pipeo) < 0) {
  427.     close (pipei[0]); close (pipei[1]);
  428.     return NIL;
  429.   }
  430.   if ((i = fork ()) < 0) {    /* make inferior process */
  431.     close (pipei[0]); close (pipei[1]);
  432.     close (pipeo[0]); close (pipeo[1]);
  433.     return NIL;
  434.   }
  435.   if (i) {            /* parent? */
  436.     close (pipei[1]);        /* close child's side of the pipes */
  437.     close (pipeo[0]);
  438.   }
  439.   else {            /* child */
  440.     dup2 (pipei[1],1);        /* parent's input is my output */
  441.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  442.     close (pipei[0]); close (pipei[1]);
  443.     dup2 (pipeo[0],0);        /* parent's output is my input */
  444.     close (pipeo[0]); close (pipeo[1]);
  445.                 /* now run it */
  446.     execl ("/usr/ucb/resh","resh",hostname,"exec",service,0);
  447.     _exit (1);            /* spazzed */
  448.   }
  449.  
  450.                 /* create TCP/IP stream */
  451.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  452.                 /* copy official host name */
  453.   stream->host = cpystr (hostname);
  454.                 /* get local name */
  455.   gethostname (hostname,MAILTMPLEN-1);
  456.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  457.                   host_name->h_name : hostname);
  458.   stream->tcpsi = pipei[0];    /* init sockets */
  459.   stream->tcpso = pipeo[1];
  460.   stream->ictr = 0;        /* init input counter */
  461.   return stream;        /* return success */
  462. }
  463.  
  464. /* TCP/IP receive line
  465.  * Accepts: TCP/IP stream
  466.  * Returns: text line string or NIL if failure
  467.  */
  468.  
  469. char *tcp_getline (stream)
  470.     TCPSTREAM *stream;
  471. {
  472.   int n,m;
  473.   char *st,*ret,*stp;
  474.   char c = '\0';
  475.   char d;
  476.                 /* make sure have data */
  477.   if (!tcp_getdata (stream)) return NIL;
  478.   st = stream->iptr;        /* save start of string */
  479.   n = 0;            /* init string count */
  480.   while (stream->ictr--) {    /* look for end of line */
  481.     d = *stream->iptr++;    /* slurp another character */
  482.     if ((c == '\015') && (d == '\012')) {
  483.       ret = (char *) fs_get (n--);
  484.       memcpy (ret,st,n);    /* copy into a free storage string */
  485.       ret[n] = '\0';        /* tie off string with null */
  486.       return ret;
  487.     }
  488.     n++;            /* count another character searched */
  489.     c = d;            /* remember previous character */
  490.   }
  491.                 /* copy partial string from buffer */
  492.   memcpy ((ret = stp = (char *) fs_get (n)),st,n);
  493.                 /* get more data from the net */
  494.   if (!tcp_getdata (stream)) return NIL;
  495.                 /* special case of newline broken by buffer */
  496.   if ((c == '\015') && (*stream->iptr == '\012')) {
  497.     stream->iptr++;        /* eat the line feed */
  498.     stream->ictr--;
  499.     ret[n - 1] = '\0';        /* tie off string with null */
  500.   }
  501.                 /* else recurse to get remainder */
  502.   else if (st = tcp_getline (stream)) {
  503.     ret = (char *) fs_get (n + 1 + (m = strlen (st)));
  504.     memcpy (ret,stp,n);        /* copy first part */
  505.     memcpy (ret + n,st,m);    /* and second part */
  506.     fs_give ((void **) &stp);    /* flush first part */
  507.     fs_give ((void **) &st);    /* flush second part */
  508.     ret[n + m] = '\0';        /* tie off string with null */
  509.   }
  510.   return ret;
  511. }
  512.  
  513. /* TCP/IP receive buffer
  514.  * Accepts: TCP/IP stream
  515.  *        size in bytes
  516.  *        buffer to read into
  517.  * Returns: T if success, NIL otherwise
  518.  */
  519.  
  520. long tcp_getbuffer (stream,size,buffer)
  521.     TCPSTREAM *stream;
  522.     unsigned long size;
  523.     char *buffer;
  524. {
  525.   unsigned long n;
  526.   char *bufptr = buffer;
  527.   while (size > 0) {        /* until request satisfied */
  528.     if (!tcp_getdata (stream)) return NIL;
  529.     n = min (size,stream->ictr);/* number of bytes to transfer */
  530.                 /* do the copy */
  531.     memcpy (bufptr,stream->iptr,n);
  532.     bufptr += n;        /* update pointer */
  533.     stream->iptr +=n;
  534.     size -= n;            /* update # of bytes to do */
  535.     stream->ictr -=n;
  536.   }
  537.   bufptr[0] = '\0';        /* tie off string */
  538.   return T;
  539. }
  540.  
  541.  
  542. /* TCP/IP receive data
  543.  * Accepts: TCP/IP stream
  544.  * Returns: T if success, NIL otherwise
  545.  */
  546.  
  547. long tcp_getdata (stream)
  548.     TCPSTREAM *stream;
  549. {
  550.   struct pollfd pollfd;
  551.   int pollstatus;
  552.   if (stream->tcpsi < 0) return NIL;
  553.   pollfd.fd = stream->tcpsi;    /* initialize selection vector */
  554.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  555.     pollfd.events = POLLIN;    /* block and read */
  556.     /* Note: am not sure here that it wouldn't also be a good idea to
  557.     restart poll() on EINTR, if SIGCHLD or whatever are expected.    DC */
  558.     while (((pollstatus = poll (&pollfd,1,-1)) < 0) && (errno == EAGAIN));
  559.     if (!pollstatus ||
  560.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  561.       close (stream->tcpsi);    /* nuke the socket */
  562.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  563.       stream->tcpsi = stream->tcpso = -1;
  564.       return NIL;
  565.     }
  566.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  567.   }
  568.   return T;
  569. }
  570.  
  571. /* TCP/IP send string as record
  572.  * Accepts: TCP/IP stream
  573.  *        string pointer
  574.  * Returns: T if success else NIL
  575.  */
  576.  
  577. long tcp_soutr (stream,string)
  578.     TCPSTREAM *stream;
  579.     char *string;
  580. {
  581.   return tcp_sout (stream,string,(unsigned long) strlen (string));
  582. }
  583.  
  584.  
  585. /* TCP/IP send string
  586.  * Accepts: TCP/IP stream
  587.  *        string pointer
  588.  *        byte count
  589.  * Returns: T if success else NIL
  590.  */
  591.  
  592. long tcp_sout (stream,string,size)
  593.     TCPSTREAM *stream;
  594.     char *string;
  595.     unsigned long size;
  596. {
  597.   int i;
  598.   struct pollfd pollfd;
  599.   int pollstatus;
  600.   pollfd.fd = stream->tcpso;    /* initialize selection vector */
  601.   pollfd.events = POLLOUT;
  602.   if (stream->tcpso < 0) return NIL;
  603.   while (size > 0) {        /* until request satisfied */
  604.     while (((pollstatus = poll (&pollfd,1,-1)) < 0) && (errno == EAGAIN));
  605.     if (!pollstatus ||
  606.     ((i = write (stream->tcpso,string,size)) < 0)) {
  607.       puts (strerror (errno));
  608.       close (stream->tcpsi);    /* nuke the socket */
  609.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  610.       stream->tcpsi = stream->tcpso = -1;
  611.       return NIL;
  612.     }
  613.     size -= i;            /* count this size */
  614.     string += i;
  615.   }
  616.   return T;            /* all done */
  617. }
  618.  
  619. /* TCP/IP close
  620.  * Accepts: TCP/IP stream
  621.  */
  622.  
  623. void tcp_close (stream)
  624.     TCPSTREAM *stream;
  625. {
  626.  
  627.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  628.     close (stream->tcpsi);    /* nuke the socket */
  629.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  630.     stream->tcpsi = stream->tcpso = -1;
  631.   }
  632.                 /* flush host names */
  633.   fs_give ((void **) &stream->host);
  634.   fs_give ((void **) &stream->localhost);
  635.   fs_give ((void **) &stream);    /* flush the stream */
  636. }
  637.  
  638.  
  639. /* TCP/IP get host name
  640.  * Accepts: TCP/IP stream
  641.  * Returns: host name for this stream
  642.  */
  643.  
  644. char *tcp_host (stream)
  645.     TCPSTREAM *stream;
  646. {
  647.   return stream->host;        /* return host name */
  648. }
  649.  
  650.  
  651. /* TCP/IP get local host name
  652.  * Accepts: TCP/IP stream
  653.  * Returns: local host name
  654.  */
  655.  
  656. char *tcp_localhost (stream)
  657.     TCPSTREAM *stream;
  658. {
  659.   return stream->localhost;    /* return local host name */
  660. }
  661.  
  662. /* Emulator for BSD gethostid() call
  663.  * Returns: unique identifier for this machine
  664.  */
  665.  
  666. long gethostid ()
  667. {
  668.   /* No gethostid() here, so just fake it and hope things turn out okay. */
  669.   return (0L);
  670. }
  671.  
  672.  
  673. /* Emulator for BSD random() call
  674.  * Returns: long random number
  675.  */
  676.  
  677. long random ()
  678. {
  679.   static int beenhere = 0;
  680.   if (!beenhere) {
  681.     beenhere = 1;
  682.     srand48 (getpid ());
  683.   }
  684.   return lrand48 ();
  685. }
  686.  
  687. /* Emulator for BSD scandir() call
  688.  * Accepts: directory name
  689.  *        destination pointer of names array
  690.  *        selection function
  691.  *        comparison function
  692.  * Returns: number of elements in the array or -1 if error
  693.  */
  694.  
  695. #define DIRSIZ(d) d->d_reclen
  696.  
  697. int scandir (dirname,namelist,select,compar)
  698.     char *dirname;
  699.     struct dirent ***namelist;
  700.     int (*select) ();
  701.     int (*compar) ();
  702. {
  703.   struct dirent *p,*d,**names;
  704.   int nitems;
  705.   struct stat stb;
  706.   long nlmax;
  707.   DIR *dirp = opendir (dirname);/* open directory and get status poop */
  708.   if ((!dirp) || (fstat (dirp->dd_fd,&stb) < 0)) return -1;
  709.   nlmax = stb.st_size / 24;    /* guesstimate at number of files */
  710.   names = (struct dirent **) fs_get (nlmax * sizeof (struct dirent *));
  711.   nitems = 0;            /* initially none found */
  712.   while (d = readdir (dirp)) {    /* read directory item */
  713.                 /* matches select criterion? */
  714.     if (select && !(*select) (d)) continue;
  715.                 /* get size of dirent record for this file */
  716.     p = (struct dirent *) fs_get (DIRSIZ (d));
  717.     p->d_ino = d->d_ino;    /* copy the poop */
  718.     p->d_off = d->d_off;
  719.     p->d_reclen = d->d_reclen;
  720.     strcpy (p->d_name,d->d_name);
  721.     if (++nitems >= nlmax) {    /* if out of space, try bigger guesstimate */
  722.       nlmax *= 2;        /* double it */
  723.       fs_resize ((void **) names,nlmax * sizeof (struct dirent *));
  724.     }
  725.     names[nitems - 1] = p;    /* store this file there */
  726.   }
  727.   closedir (dirp);        /* done with directory */
  728.                 /* sort if necessary */
  729.   if (nitems && compar) qsort (names,nitems,sizeof (struct dirent *),compar);
  730.   *namelist = names;        /* return directory */
  731.   return nitems;        /* and size */
  732. }
  733.  
  734. /* Emulator for BSD flock() call
  735.  * Accepts: file descriptor
  736.  *        operation bitmask
  737.  * Returns: 0 if successful, -1 if failure
  738.  * Note: this emulator does not handle shared locks
  739.  */
  740.  
  741. int flock (fd, operation)
  742.     int fd;
  743.     int operation;
  744. {
  745.   int func;
  746.   off_t offset = lseek (fd,0,L_INCR);
  747.   switch (operation & ~LOCK_NB){/* translate to lockf() operation */
  748.   case LOCK_EX:            /* exclusive */
  749.   case LOCK_SH:            /* shared */
  750.     func = (operation & LOCK_NB) ? F_TLOCK : F_LOCK;
  751.     break;
  752.   case LOCK_UN:            /* unlock */
  753.     func = F_ULOCK;
  754.     break;
  755.   default:            /* default */
  756.     errno = EINVAL;
  757.     return -1;
  758.   }
  759.   lseek (fd,0,L_SET);        /* position to start of the file */
  760.   func = lockf (fd,func,0);    /* do the lockf() */
  761.   lseek (fd,offset,L_SET);    /* restore prior position */
  762.   return func;
  763. }
  764.  
  765.  
  766. /* Emulator for BSD gettimeofday() call
  767.  * Accepts: address where to write timeval information
  768.  *        address where to write timezone information
  769.  * Returns: 0 if successful, -1 if failure
  770.  */
  771.  
  772. int gettimeofday (tp,tzp)
  773.     struct timeval *tp;
  774.     struct timezone *tzp;
  775. {
  776.   tp->tv_sec = time (0);    /* time since 1-Jan-70 00:00:00 GMT in secs */
  777.                 /* others aren't used in current code */
  778.   if (tzp) tzp->tz_minuteswest = tzp->tz_dsttime = 0;
  779.   tp->tv_usec = 0;
  780.   return 0;
  781. }
  782.  
  783.  
  784. /* Emulator for BSD utimes() call
  785.  * Accepts: file name
  786.  *        timeval vector for access and updated time
  787.  * Returns: 0 if successful, -1 if failure
  788.  */
  789.  
  790. int utimes (file,tvp)
  791.     char *file;
  792.     struct timeval tvp[2];
  793. {
  794.   struct utimbuf tb;
  795.   tb.actime = tvp[0].tv_sec;    /* accessed time */
  796.   tb.modtime = tvp[1].tv_sec;    /* updated time */
  797.   return utime (file,&tb);
  798. }
  799.